package com.v1.video.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.adapter.CarouselAdapter;
import com.v1.video.adapter.CibnAdapter;
import com.v1.video.domain.Carousel;
import com.v1.video.domain.CarouselEntity;
import com.v1.video.domain.CibnEntity;
import com.v1.video.engine.NetEngine;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;
import com.v1.video.view.CircleFlowIndicator;
import com.v1.video.view.HeaderGridView;
import com.v1.video.view.PullToRefreshHeaderGridView;
import com.v1.video.view.ViewFlow;

import java.util.List;

public class CibnFragment extends V1BaseFragment {

	private final String TAG = "CibnFragment";
	private View mView,mViewHeader, mEmptyView;
	private LayoutInflater mInflater;
	private HeaderGridView mGridView;
	private PullToRefreshHeaderGridView mRefreshGridView;
	private ViewFlow mViewflow;
	private CircleFlowIndicator mFlowIndicator;
	private String mCid;
	private String mGenre;
	private boolean isLoad = true;
	private CibnAdapter mAdapter;
	private int mCurIndex = 1;
	private CarouselAdapter mImageAdapter;

	public static CibnFragment newInstance(String tag,String genre) {
		CibnFragment f = new CibnFragment();
		Bundle bundle = new Bundle();
		bundle.putString("tag", tag);
		bundle.putString("genre", genre);
		f.setArguments(bundle);
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		mView = inflater.inflate(R.layout.fragment_cibn, container, false);
		initView();
		setListener();
		initData();
		return mView;
	}

	private void initView() {
		mEmptyView = mInflater.inflate(R.layout.fragment_no_content, null);
		mViewHeader = mInflater
				.inflate(R.layout.fragment_classify_header, null);
		mRefreshGridView = (PullToRefreshHeaderGridView) mView
				.findViewById(R.id.gv_gridView);
		mGridView = mRefreshGridView.getRefreshableView();
		mRefreshGridView.setScrollingWhileRefreshingEnabled(false);
		mRefreshGridView.setMode(Mode.PULL_FROM_START);
		mGridView.addHeaderView(mViewHeader);
		mViewflow = (ViewFlow) mViewHeader.findViewById(R.id.vf_viewflow);
		RelativeLayout mLayViewflow = (RelativeLayout) mViewHeader
				.findViewById(R.id.lay_viewflow);
		mViewflow.setViewGroup(mGridView);
		int width = Utils.getScreenWidth(this.getActivity());
		int height = width / 2;
		mLayViewflow.setLayoutParams(new LinearLayout.LayoutParams(width,
				height));
		mFlowIndicator = (CircleFlowIndicator) mViewHeader
				.findViewById(R.id.flowIndicator);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void setListener() {
		mEmptyView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (mRefreshGridView != null) {
					mRefreshGridView.doPullRefreshing(100);
				}
			}
		});
		mRefreshGridView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				if (Helper.checkConnection(getActivity())) {
					getCarouselData();
					getServerData();
				} else {
					mHandler.sendEmptyMessageDelayed(0, 100);
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				if (Helper.checkConnection(getActivity())) {
					getServerData();
				} else {
					mHandler.sendEmptyMessageDelayed(0, 100);
				}
			}
		});

		mGridView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					ImageLoader.getInstance().resume();
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					ImageLoader.getInstance().pause();
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					ImageLoader.getInstance().pause();
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
			}

		});
	}

	private void initData() {
		mCid = getArguments().getString("tag");
		mGenre = getArguments().getString("genre");
		mAdapter = new CibnAdapter(getActivity(),mCid, mGenre);
		mGridView.setAdapter(mAdapter);
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if (mRefreshGridView != null) {
					mRefreshGridView.onRefreshComplete();
				}
				setEmptyView();
				showToast(R.string.net_no_click);
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 设置空的界面显示
	 */
	private void setEmptyView() {
		View view = mGridView.getEmptyView();
		if (view == null) {
			mGridView.setEmptyView(mEmptyView);
		}
		if (mRefreshGridView != null) {
			mRefreshGridView.setMode(Mode.PULL_FROM_START);
		}
	}

	@Override
	public void refresh(Object tag) {
		// TODO Auto-generated method stub
		super.refresh(tag);
		if (isLoad == true) {
			isLoad = false;
			if (mRefreshGridView != null) {
				mRefreshGridView.doPullRefreshing(50);
			}
		}
	}
	
	private void getCarouselData() {
		new NetEngine().getCarouselData(this.getActivity(), mCid, "1",
				new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String keyId) {
						// TODO Auto-generated method stub
						try {
							if (object != null) {
								CarouselEntity entity = (CarouselEntity) object;
								if (entity != null && entity.getBody() != null) {
									showViewFlow(entity.getBody().getData());
								}
							}
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						Logger.e(TAG, message);
					}

				});
	}

	private void getServerData() {
		String url = String.format(Constant.CIBN_CLASSIFY_LIST, mCid,
				mCurIndex, Utils.getPhoneOsVersion());
		Logger.i(TAG, "CIBN频道列表Url="+url);
		RequestManager.getInstance().getRequest(this.getActivity(), url,
				CibnEntity.class, mCid, new OnResponseListener() {

					@Override
					public void onSuccess(Object object, int code,
							String message, String keyId) {
						// TODO Auto-generated method stub
						if (mRefreshGridView != null) {
							mRefreshGridView.onRefreshComplete();
						}
						try {
							if (object != null) {
								CibnEntity entity = (CibnEntity) object;
								if (entity != null && entity.getBody()!=null && entity.getBody().getRows() != null
										&& entity.getBody().getRows().size() > 0) {
									if (mAdapter != null) {
										if (mCurIndex == 1) {
											mAdapter.clearLstData();
										}
										mAdapter.setLstData(entity.getBody().getRows());
									}
									if ((mCurIndex + 1) < entity.getBody()
											.getTotalPages()) {
										mCurIndex++;
										if (mRefreshGridView != null) {
											mRefreshGridView.setMode(Mode.BOTH);
										}
									} else {
										if (mRefreshGridView != null) {
											mRefreshGridView
													.setMode(Mode.PULL_FROM_START);
										}
									}
								}
							}
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}

					@Override
					public void onFailure(int code, String message) {
						// TODO Auto-generated method stub
						if (mRefreshGridView != null) {
							mRefreshGridView.onRefreshComplete();
						}
					}

				});
	}
	
	/**
	 * 显示轮播图
	 */
	private void showViewFlow(List<Carousel> lstCarousel) {
		if (lstCarousel != null && lstCarousel.size() > 0) {
			try {
				int perWidth = (int) this.getResources().getDimension(
						R.dimen.cf_indicator_per_width);
				int width = lstCarousel.size() * perWidth;
				ViewGroup.LayoutParams params= mFlowIndicator.getLayoutParams();
				params.width = width;
				mFlowIndicator.setLayoutParams(params);
				mImageAdapter = new CarouselAdapter(getActivity());
				mImageAdapter.setLstData(lstCarousel);
				mViewflow.setAdapter(mImageAdapter);
				mViewflow.setmSideBuffer(lstCarousel.size());
				mViewflow.setFlowIndicator(mFlowIndicator);
				if (lstCarousel.size() > 1) {
					mViewflow.setTimeSpan(10000);
					mViewflow.setSelection(lstCarousel.size() * 1000); // 设置初始位置
					mViewflow.startAutoFlowTimer(); // 启动自动播放
				} else {
					mViewflow.stopAutoFlowTimer();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isLoad = true;
		if (mAdapter != null) {
			mAdapter = null;
		}
		RequestManager.getInstance().requestCancel(this.getActivity(), mCid);
	}
}
